package org.prj;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InitServlet2 extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7908509740879314932L;

	private IMyObject obj;
	private ClassLoader parentClassLoader;

	private MyClassLoader classLoader;
	
	
	@Override
	public void init(ServletConfig config) throws ServletException {	
		super.init(config);
		
		parentClassLoader = this.getClass().getClassLoader();// MyClassLoader.class.getClassLoader();
	    classLoader = new MyClassLoader(parentClassLoader);
	    Class myObjectClass = null;
		try {
			myObjectClass = classLoader.loadClass("org.prj.MyObject");
			obj=(IMyObject) myObjectClass.newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

//	    obj=(IMyObject) myObjectClass.newInstance();
//
//	    //create new class loader so classes can be reloaded.
//	    classLoader = new MyClassLoader(parentClassLoader);
//	    myObjectClass = classLoader.loadClass("org.prj.MyObject");
//
//	    //object1 = (AnInterface2)       myObjectClass.newInstance();
//	    //object2 = (MyObjectSuperClass) myObjectClass.newInstance();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if(req.getParameter("reload")!=null){
			Class myObjectClass = null;
			classLoader = new MyClassLoader(parentClassLoader);
			//classLoader.reload();
			try {
				myObjectClass = classLoader.loadClass("org.prj.MyObject");
				obj=(IMyObject) myObjectClass.newInstance();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		
		resp.getWriter().write(obj.saluta());
	}
}
